package com.theaf.core.error;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class SmException extends RuntimeException implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 认证错误
	 */
	public static final int AUTH_ERROR = -1;
	/**
	 * 请求成功，并且接口正常返回数据
	 */
	public static final int SUCCESS_CODE = 1000;
	/**
	 * 请求失败，未知错误（系统层面异常，没有定义异常信息的）
	 */
	public static final int ERR_SYS_UNKNOWN = 9999;
	/**
	 * 请求失败，系统层面的检查异常
	 */
	public static final int ERR_SYS_CHECK = 9998;
	/**
	 * 请求拒绝，请求频率太高
	 */
	public static final int ERR_REQ_FRU = 9997;
	/**
	 * 请求失败，请求参数错误
	 */
	public static final int ERR_REQ_ARG_NOT_VALID = 9900;
	/**
	 * 请求失败，业务检查异常
	 */
	public static final int ERR_REQ_LOG_NOT_VALID = 9901;
	/**
	 * 请求失败，用户信息认证失败
	 */
	public static final int ERR_REQ_AUTH_FAILED = 1401;
	/**
	 * 请求拒绝，（禁止） 服务器拒绝请求，用户无访问权限
	 */
	public static final int ERR_REQ_FORBIDDEN = 1403;
			

	private static Properties exceptionDefine;
	private int status;
	private String code;
	private String message;

	static {
		if (exceptionDefine == null) {
			exceptionDefine = new Properties();
			try {
				exceptionDefine.load(
						SmException.class.getClassLoader().getResourceAsStream("exception_define.properties"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public SmException(int status) {
		super(getErrorDefine(String.valueOf(status)));
		this.message = getErrorDefine(String.valueOf(status));
		this.status = status;
	}

	private static String getErrorDefine(String status) {
		if (!exceptionDefine.containsKey(status)) {
			return "未定义异常";
		}
		String mess = exceptionDefine.getProperty(status);
		return mess == null ? "未定义异常" : mess;
	}

	public SmException(int status, String code, String message) {
		super(message);
		this.status = status;
		this.code = code;
		this.message = message;
	}

	public SmException(int status, Throwable cause) {
		this(status);
		this.initCause(cause);
	}

	public SmException(Throwable cause) {
		super(cause.getMessage());
		this.status = ERR_SYS_UNKNOWN;
		this.message = "系统异常，请稍后再试！";
		this.initCause(cause);
	}

	public Map getException() {
		Map exception = new HashMap();
		exception.put("status", status);
		exception.put("message", message);
		return exception;
	}

	@Override
    public String getMessage() {
		return message;
	}

	public int getStatus() {
		return status;
	}

	public String getCode() {
		return code;
	}
}
